package com.duguo.dynamicmvc.view.resource;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.duguo.dynamicmvc.support.ModelAndView;
import com.duguo.dynamicmvc.support.ModelAndViewImpl;
import com.duguo.dynamicmvc.support.pathinfo.PathInfo;
import com.duguo.dynamicmvc.view.RenderedView;

public class FileSystemResourceHandler{
	
	private File _fileSystemDir;
	
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response, PathInfo pathInfo) throws Exception {
		File resourceFile=new File(_fileSystemDir,pathInfo.getRemainPath());		
		if(resourceFile.exists() && resourceFile.isFile()) {
			Resource fileResource=new FileSystemResource(resourceFile);
			return new ModelAndViewImpl(new ResourceView(fileResource));
		}else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return RenderedView.RENDERED_MODEL_AND_VIEW;
		}
	}
	
	public String getPath() {
		return _fileSystemDir!=null?_fileSystemDir.getPath():null;
	}

	public void setPath(String path) {
		_fileSystemDir=new File(path);
		_fileSystemDir=new File(_fileSystemDir.getAbsolutePath());
		if(!_fileSystemDir.exists() || !_fileSystemDir.isDirectory()) {
			throw new RuntimeException(path+" doesn't exist or is not a direcoty");
		}
	}
}
